package com.genius.workflow.interceptor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommonInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object handler) throws Exception {
    	String path = request.getContextPath();
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        request.setAttribute("basePath", basePath);
        
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
 
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
 
        boolean isPage = method.getReturnType().equals(String.class);
        boolean isJosn = !method.isAnnotationPresent(ResponseBody.class);
        boolean isController = (!hm.getBeanType().isAnnotationPresent(RestController.class) || !hm.getBeanType().isAnnotationPresent(Controller.class));
                //controller_response_is_view 这个表示controller的返回响应类型是页面
        request.setAttribute("method_return_is_view", isPage && isJosn && isController);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
